import './index.scss'
import 'dayjs/locale/zh-cn'

import {
  AppstoreAddOutlined,
  AppstoreOutlined,
  BarsOutlined,
  CommentOutlined,
  ContainerOutlined,
  HomeOutlined,
  InsertRowLeftOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  ShoppingOutlined,
  TagOutlined
} from '@ant-design/icons'
import { Button, ConfigProvider, Layout, Menu, theme } from 'antd'
import { Outlet, useNavigate } from 'react-router-dom'
import React, { FC, useEffect, useState, useTransition } from 'react'
import {
  setActiveKey,
  setSelectedKeys,
  setTabItems
} from '@/store/modules/front'
import { useAppDispatch, useAppSelector } from '@/store/hooks'

import Avatar from '@/components/Avatar'
import { IntlProvider } from 'react-intl'
import type { MenuProps } from 'antd'
import PubSub from 'pubsub-js'
import { Root } from '@/types'
import { Root2 } from '@/types/menuItem'
import TabsViews from '@/components/tabs'
import Theme from '@/components/Theme'
import Translate from '@/components/Translate'
import { activeTabs } from '@/store/modules/tabs'
import classNames from 'classnames'
import dayjs from 'dayjs'
import io from 'socket.io-client'
import { localeConfig } from '@/Locales'

/* eslint-disable react-hooks/rules-of-hooks */

// 框架语言配置

dayjs.locale('zh-cn')
const { Header, Sider, Content } = Layout

const index: FC = () => {
  const navigate = useNavigate()
  const [socket, setSocket] = useState<any>(null)
  const [collapsed, setCollapsed] = useState(false)
  // 获取redux数据
  const {
    Menus,
    tabItems,
    selectedKeys,
    definedLocale,
    currentTheme,
    antdLocale
  } = useAppSelector((state) => state.front)
  const dispatch = useAppDispatch()
  // 转换icon字符串为组件（递归算法）
  const iconMapping: { [key: string]: React.ComponentType<any> } = {
    HomeOutlined,
    ShoppingOutlined,
    CommentOutlined,
    ContainerOutlined,
    InsertRowLeftOutlined,
    AppstoreAddOutlined,
    AppstoreOutlined,
    BarsOutlined,
    TagOutlined
  }
  useEffect(() => {
    const socket = io('http://localhost:4000')
    setSocket(socket)

    // 默认socket.io-client包含一个心跳机制，定期检查连接状态，所以不需要手动定时器进行心跳的设置，避免重复发送心跳
    // 设置心跳机制
    // const heartbeat = setInterval(() => {
    //   if (socket) {
    //     socket.emit('heartbeat')
    //   }
    // }, 120000)
    return () => {
      if (socket) {
        socket.disconnect()
      }
      // clearInterval(heartbeat)
    }
  }, [])
  useEffect(() => {
    if (socket) {
      const token = PubSub.subscribe('change', (msg, data) => {
        socket.emit('changeData', data)
        socket.on('getData', (data: string) => {
          const parsedData = JSON.parse(data)
          console.log('获取最新表格数据', parsedData)
          PubSub.publish('setData', parsedData)
        })
      })
      return () => {
        if (socket) {
          socket.disconnect()
        }
        PubSub.unsubscribe(token)
      }
    }
  }, [socket])
  const transformMenu = (menu: any) => {
    menu = menu.filter(
      (item: Root2) =>
        item.key !== 'orderDetails' &&
        item.key !== 'returns' &&
        item.key !== 'roleUpdate'
    )
    return menu.map((item: Root2) => {
      const IconComponent = iconMapping[item.icon]
      const newItem = {
        ...item,
        label: item.label[definedLocale as string],
        icon: IconComponent ? <IconComponent /> : null
      }
      if (item.children) {
        newItem.children = transformMenu(item.children)
      }
      return newItem
    })
  }
  const newMenus: Root[] = transformMenu(Menus)

  const {
    token: { colorBgContainer, borderRadiusLG }
  } = theme.useToken()

  // 解决页面跳转报错
  const [isPending, startTransition] = useTransition()
  // 获取头部标签
  const handleClick: MenuProps['onClick'] = (event) => {
    const label: string = findLabel(newMenus, event.key)
    addTabs(label, event.key)
    dispatch(setActiveKey(`/${event.key}`))

    dispatch(setSelectedKeys([event.key]))
    dispatch(activeTabs(event.key))
    // 切换路由
    startTransition(() => {
      if (event.key === 'index') {
        console.log(isPending)
        navigate('/')
      } else {
        navigate(event.key)
      }
    })
  }
  // 递归寻找label
  const findLabel = (menus: Root[], key: string) => {
    for (const item of menus) {
      if (item.key === key) {
        return item.label
      }
      if (item.children) {
        const label: string | undefined = findLabel(item.children, key)
        if (label) {
          return label
        }
      }
    }
    return undefined
  }

  // 添加自定义tabs标签
  const addTabs = (label: string, key: string) => {
    // 判断是否已经存在该标签
    const isExist = tabItems.findIndex((item) => item.key === `/${key}`)
    if (isExist !== -1) return

    const newPanes = [...tabItems]
    newPanes.push({
      label: label,
      key: `/${key}`
    })
    dispatch(setTabItems(newPanes))
    dispatch(setActiveKey(key))
  }
  return (
    <>
      <ConfigProvider
        locale={antdLocale}
        theme={{
          algorithm:
            currentTheme === 'dark'
              ? theme.darkAlgorithm
              : theme.defaultAlgorithm
        }}
      >
        <IntlProvider
          locale={definedLocale}
          messages={localeConfig[definedLocale]}
        >
          <Layout className="layout" hasSider>
            <Sider
              breakpoint="lg"
              onBreakpoint={(broken) => {
                if (broken) {
                  setCollapsed(true)
                } else {
                  setCollapsed(false)
                }
              }}
              trigger={null}
              collapsible
              collapsed={collapsed}
              className={classNames('sider-menus', {
                'dark-sider': currentTheme === 'dark',
                'light-sider': currentTheme !== 'dark'
              })}
            >
              <div className="demo-logo-vertical" />
              <Menu
                id="menu"
                selectedKeys={selectedKeys}
                defaultSelectedKeys={['']}
                defaultOpenKeys={['sub1']}
                mode="inline"
                theme={currentTheme}
                items={newMenus}
                style={{ fontSize: '17px' }}
                onClick={(e) => handleClick(e)}
              />
            </Sider>
            <Layout
              style={{
                transition: 'margin-left 0.28s',
                marginLeft: collapsed ? '80px' : '200px'
              }}
              className="layout-content"
            >
              <Header
                style={{
                  background: colorBgContainer,
                  borderRadius: borderRadiusLG
                }}
                className={classNames('layout-header', {
                  'dark-sider': currentTheme === 'dark',
                  'light-sider': currentTheme !== 'dark'
                })}
                id="header-setting"
              >
                <Button
                  id="collapsedbtn"
                  type="text"
                  icon={
                    collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />
                  }
                  onClick={() => setCollapsed(!collapsed)}
                  className="menu-button"
                />
                {/* 主题切换 */}
                <Theme></Theme>
                {/* 中英文切换 */}
                <Translate></Translate>
                <Avatar></Avatar>
              </Header>
              <div className="tabs">
                <TabsViews></TabsViews>
              </div>
              <div className="content-layout">
                <Content
                  style={{
                    background: colorBgContainer,
                    borderRadius: borderRadiusLG
                  }}
                  className={classNames('content-router', {
                    'dark-sider': currentTheme === 'dark',
                    'light-sider': currentTheme !== 'dark'
                  })}
                >
                  <Outlet></Outlet>
                </Content>
              </div>
            </Layout>
          </Layout>
        </IntlProvider>
      </ConfigProvider>
    </>
  )
}

export default index
